#!BPY

"""
Name: '3Danim (.txt)'
Blender: 243
Group: 'Export'
Tooltip: 'export an animated text format.'
"""

__author__ = 'V Vamsi Krishna'
__version__ = '0.1'
__url__ = ["3danim project, http://code.google.com/p/3danim",
     "", "blender", "blenderartists.org"]
__email__ = ["V.Vamsi Krishna, vamsikrishna.v:gmail*com", "3danim export"]
__bpydoc__ = """This script Exports animated 3d models in 3danim text format."""

import Blender
from Blender import *
from Blender.Armature.NLA import *
from Blender.Scene import *
from Blender import Window


def call_back(filename):
    if not(filename.endswith(".txt")):
        filename = filename + ".txt"

    try:
        fp = open(filename, "r")
        fp.close()
        result = Draw.PupMenu("SaveOver?%t|Yes|No")
        if result == 2:
            return
    except:
        print "Creating File ", filename
        pass
    fp = open(filename, "w")
    #mesh_objs = Blender.Object.GetSelected()
    mesh_objs =  Scene.GetCurrent().objects
    mesh_obj = mesh_objs[0]
    armature_obj = mesh_objs[0]
    for obj in mesh_objs:
        if obj.getType() == "Mesh":
            mesh_obj = obj
        elif obj.getType() == "Armature":
            armature_obj = obj
    
    #    return
    mesh = mesh_obj.getData(False, True)
    mesh = mesh.__copy__()
    
    num_verts = len(mesh.verts)
    num_faces = len(mesh.faces)
    actions = GetActions()
    
    print num_verts, num_faces, len(actions.keys())
    fp.write("%d %d %d\n" % (num_verts, num_faces, len(actions.keys())))
    for face in mesh.faces:
        buff = ""
        for v in face.verts:
            print v.index, 
            buff += v.index.__str__() + " "
        print "\n",
        fp.write(buff+"\n")
        if mesh.faceUV:
            for uv in face.uv:
                fp.write('%.3f %.3f\n' % (uv[0], uv[1]))
    
    #get the actions devined on the armature
    #get their keyframes and print the vertex coords
    #do a linear interpolation of the vertieces
    for key in actions.keys():
        act = actions[key]
        act.setActive(armature_obj)
        keyframes = act.getFrameNumbers()
        print act.getName(), len(keyframes)
        fp.write(act.getName() + " %d" % len(keyframes) + "\n")
        for frame in keyframes:
            Blender.Set("curframe", frame)
            print frame
            fp.write("%d\n" % frame)
            mesh.getFromObject(mesh_obj.name)
            #-------------------------------
            #for face in mesh.faces:
            #    for v in face.verts:
            #        print v.index, 
            #    print ""
            #-------------------------------
            for vert in mesh.verts:
                fp.write('%.3f %.3f %.3f\n' % (vert.co[0], vert.co[1], vert.co[2]))

    fp.close()

defaultFileName = Blender.Get('filename')
Window.FileSelector(call_back, '3Danim Export *.txt', defaultFileName.replace('.blend', '.txt')) 
